package com.lijy.likebutton.view

import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import com.lijy.likebutton.bean.PointBean
import com.lijy.likebutton.util.DimenUtils

/**
 *@time:     2020/12/7 0007
 *@author:   Lijy

 *@description:
 */
class CountView @JvmOverloads constructor(
    context: Context,
    var mLikeNum: Int = 0,
    var mTextColor: Int = Color.parseColor("#FF6600"),
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr), View.OnClickListener {

    private var viewHeight = DimenUtils.dp2px(context, 38f)
    private var textSize: Float = DimenUtils.sp2px(context, 15f)
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)


    private var baseline = 0f
    private var textWidth = 0f
    private var textMaxHeight = textSize

    private val textPaintAlpha = 255 / textMaxHeight
    private var textPaintAlphaFirst = 0
    private var textPaintAlphaSecond = 0

    //true:     +1操作
    //false:    -1操作
    private var flag = true
//    var num = 45

    /**
     * [0] 未改变的文字
     * [1]  改变之前的文字
     * [2]  改变之后的文字
     */
    private val textList = arrayOfNulls<String>(3)
    private val pointList: MutableList<PointBean> = ArrayList()

    private var newMoveY = 0f
    private var oldMoveY = 0f
        set(value) {
            field = value
            Log.e("****Log****", value.toString())
            //true:     +1操作
            //false:    -1操作
            if (flag) {
                newMoveY = value + textMaxHeight
                textPaintAlphaFirst = (value * textPaintAlpha).toInt()
                textPaintAlphaSecond = ((textMaxHeight - value) * textPaintAlpha).toInt()
            } else {
                newMoveY = value - textMaxHeight
                textPaintAlphaFirst = ((textMaxHeight - value) * textPaintAlpha).toInt()
                textPaintAlphaSecond = (value * textPaintAlpha).toInt()
            }

            calculateTextCoordinate()
            postInvalidate()
        }

    private fun moveYAnim() {
        val anim = ObjectAnimator.ofFloat(
            this, "oldMoveY",
            0f, if (flag) -textMaxHeight else textMaxHeight
        )
        anim.duration = 200
        anim.start()

    }

    //计算要改变的文字长度
    fun calculateChangeText(change: Int) {
        if (change == 0) {
            textList[0] = mLikeNum.toString()
            textList[1] = ""
            textList[2] = ""
            return
        }

        val oldNum = mLikeNum.toString()
        val newNum = (mLikeNum + change).toString()

        for (i in oldNum.indices) {
            val oldChar = oldNum[i]
            val newChar = newNum[i]
            if (oldChar != newChar) {
                textList[0] = if (i == 0) "" else newNum.substring(0, i)
                textList[1] = oldNum.substring(i)
                textList[2] = newNum.substring(i)
                break
            }

        }
        mLikeNum += change
        flag = change > 0
        moveYAnim()
    }

    private fun calculateTextCoordinate() {
        val content = mLikeNum.toString()
        //获取每个字符的宽度
        textWidth = textPaint.measureText(content) / content.length
        //不改变的文字的宽度
        val unChangeText = textList[0]?.length?.times(textWidth)
        //获取基线
        val fontMetricsInt = textPaint.fontMetricsInt
        baseline = paddingTop + (textSize - fontMetricsInt.bottom - fontMetricsInt.top) / 2

        pointList[0].x = paddingLeft.toFloat()
        pointList[1].x = paddingLeft + unChangeText!!
        pointList[2].x = paddingLeft + unChangeText!!

        Log.e("TAG", "calculateTextCoordinate: ${height - baseline}")
        pointList[0].y = viewHeight - baseline
        pointList[1].y = viewHeight - baseline + oldMoveY
        pointList[2].y = viewHeight - baseline + newMoveY

        Log.e("TAG", "calculateTextCoordinate:- oldMoveY: ${pointList[1].y}")
        Log.i("TAG", "calculateTextCoordinate:+ oldMoveY: ${pointList[2].y}")
    }

    init {
        textPaint.textSize = textSize
        textPaint.color = mTextColor
        textPaint.style = Paint.Style.STROKE

        pointList.add(PointBean(0f, 0f))
        pointList.add(PointBean(0f, 0f))
        pointList.add(PointBean(0f, 0f))

        //计算要变化的文字的长度
        calculateChangeText(0)
        //计算每段文字的开始坐标
        calculateTextCoordinate()
//        setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        calculateChangeText(1)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)

        //+1是因为view的宽窄,99变100的时候会多一位，会放不下
        //因为是点赞，只有+1，-1的功能，所以不存在99变1000这种可能
        val width =
            (textWidth * (1 + mLikeNum.toString().length) + paddingLeft + paddingRight).toInt()
        val height = viewHeight.toInt()

        if (layoutParams.width == ViewGroup.LayoutParams.WRAP_CONTENT
            && layoutParams.height == ViewGroup.LayoutParams.WRAP_CONTENT
        ) {
            setMeasuredDimension(width, height)
        } else if (layoutParams.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
            setMeasuredDimension(width, heightSize)
        } else if (layoutParams.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
            setMeasuredDimension(widthSize, height)
        }
    }

    override fun onDraw(canvas: Canvas) {

        textPaint.alpha = 255
        textList[0]?.let { canvas.drawText(it, pointList[0].x, pointList[0].y, textPaint) }

        textPaint.alpha = textPaintAlphaFirst
        textList[1]?.let { canvas.drawText(it, pointList[1].x, pointList[1].y, textPaint) }

        textPaint.alpha = textPaintAlphaSecond
        textList[2]?.let { canvas.drawText(it, pointList[2].x, pointList[2].y, textPaint) }

//        Log.e("TAG", "onDraw  baseline: $baseline")
//        Log.e("TAG", "onDraw  width / 2: ${width / 2}")
//        Log.e("TAG", "onDraw  height / 2: ${height / 2}")
    }

    /*设置参数*/
    fun setLikeNum(likeNum: Int) {
        this.mLikeNum = likeNum
        calculateChangeText(0)
        requestLayout()
    }

    fun setTextColor(textColor: Int){
        this.mTextColor = textColor
        textPaint.color = mTextColor
        postInvalidate()
    }

}